package com.tang.watermake;

import com.tang.bean.WaterSensor;
import com.tang.functions.WaterSensorMapFunction;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

/**
 * 有序流内置水位线
 *
 * @author tang
 * @since 2023/6/12 15:34
 */
public class WatermarkLateDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1); // 在ENV设置的总算子

        SingleOutputStreamOperator<WaterSensor> map = env.socketTextStream("192.168.70.141", 7777)
                .map(new WaterSensorMapFunction());
        
        // 1.定义Watermark策略
        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
                // 1.1 指定watermark生成：升序的watermark，没有等待时间
                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3L))
                // 1.2 指定时间戳分配器，从数据中提取
                .withTimestampAssigner((element, recordTimestamp) -> {
                    // 返回的时间戳是毫秒
                    System.out.println("数据= " + element + "，recordTs=" + recordTimestamp);
                    return element.getTs() * 1000L;
                });

        OutputTag<WaterSensor> later = new OutputTag<>("later", Types.POJO(WaterSensor.class));
        
        // 2. 指定watermark策略
        SingleOutputStreamOperator<WaterSensor> sourceWithWatermark = map.assignTimestampsAndWatermarks(watermarkStrategy);
        SingleOutputStreamOperator<String> process = sourceWithWatermark.keyBy(WaterSensor::getId)
                // 3. 使用事件时间语义的窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .allowedLateness(Time.seconds(2L))
                .sideOutputLateData(later)
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, ProcessWindowFunction<WaterSensor, String, String, TimeWindow>.Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        long startTs = context.window().getStart();
                        long endTs = context.window().getEnd();
                        String windowStart = DateFormatUtils.format(startTs, "yyyy-MM-dd HH:mm:ss.SSS");
                        String windowEnd = DateFormatUtils.format(endTs, "yyyy-MM-dd HH:mm:ss.SSS");

                        long count = elements.spliterator().estimateSize();

                        out.collect("key=" + s + "的窗口[" + windowStart + "," + windowEnd + ")包含" + count + "条数据===>" + elements);
                    }
                });

        process.getSideOutput(later).printToErr("关窗后的迟到数据");
        process.print();
        env.execute();
    }

}
